package com.rmb.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.fastjson.JSON;
import com.rmb.common.exception.ExceptionCast;
import com.rmb.common.model.response.CommonCode;
import com.rmb.common.model.state.TaskStatus;
import com.rmb.dao.TaskExcelDao;
import com.rmb.dao.TaskInfoDao;
import com.rmb.entity.TaskExcel;
import com.rmb.entity.TaskInfo;
import com.rmb.mapper.TaskInfoMapper;
import com.rmb.service.TaskInfoService;
import com.rmb.util.ExcelModelListener;
import com.rmb.util.MultiparFileToFileUtil;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author ZhaoMuYang
 * @Date 2021/1/8 19:39
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TaskInfoServiceImpl implements TaskInfoService {
    private static final Integer MAXPAGESIZE = 100;
    private static final Integer DEFAULTPAGESIZE = 10;
    private static final Integer TOTALSIZE = 0;

    @Resource
    private TaskInfoDao taskInfoDao;

    @Resource
    private TaskInfoMapper taskInfoMapper;

    @Resource
    private TaskExcelDao dao;

    @Override
    public List<TaskInfo> findList() {
        return taskInfoDao.findAll();
    }

    /**
     * 【功能描述】：任务查询功能
     * @param taskInfo
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<TaskInfo> selectTaskInfoList(TaskInfo taskInfo, Integer pageNum, Integer pageSize) {
        //最大查询100条
        if (pageSize > MAXPAGESIZE) {
            pageSize = MAXPAGESIZE;
        }
        //默认查询10条
        if (pageSize <=TOTALSIZE) {
            pageSize = DEFAULTPAGESIZE;
        }

        List<TaskInfo> taskInfos = taskInfoMapper.selectTaskInfoList(taskInfo, pageNum, pageSize);
        return taskInfos;
    }

    /**
     * 添加任务保证任务名称唯一、任务权重不为空
     *
     * @param taskInfo
     * @return
     */
    @Override
    public TaskInfo saveTaskInfo(TaskInfo taskInfo) {
        AtomicInteger flag = new AtomicInteger(TaskStatus.NOT_IMPLEMENTED_STATUS.getStatus());
        if (taskInfo == null) {
            ExceptionCast.cast(CommonCode.PARAMETER_CANNOT_BE_EMPTY);
        }
        //查询并判断是否存在
        List<TaskInfo> taskInfos = taskInfoDao.findAll();
        taskInfos.forEach(task -> {
            if (taskInfo.getName().equals(task.getName())) {
                flag.set(TaskStatus.EXECUTOR_COTACT_STATUS.getStatus());
            }
        });
        //名称已经存在或权重等级为空抛出异常
        if (flag.get() == TaskStatus.EXECUTOR_COTACT_STATUS.getStatus() || taskInfo.getWeightLevel() == null) {
            ExceptionCast.cast(CommonCode.PARAMETER_ABNORMAL);
        }


        return taskInfoDao.save(taskInfo);
    }


    /**
     * 根据任务id删除
     * @param taskId 任务ID
     * @return 结果集
     */
    @Override
    public boolean removeTaskByTaskId(Long taskId) {
        Integer flag = TaskStatus.NOT_IMPLEMENTED_STATUS.getStatus();
        //参数是否有效
        if(taskId==null){
            ExceptionCast.cast(CommonCode.PARAM_FALL);
        }
        //状态判断
        if(TaskStatus.NOT_IMPLEMENTED_STATUS.getStatus().equals(taskInfoDao.findById(taskId).get().getExeStatus())){
            if(taskInfoMapper.removeTaskByTaskId(taskId)>TaskStatus.NOT_IMPLEMENTED_STATUS.getStatus()){
                //删除关联数据
                taskInfoMapper.removeRelevancePlan(taskId);
                taskInfoMapper.removeRelevanceInput(taskId);
                flag=TaskStatus.EXECUTOR_COTACT_STATUS.getStatus();
            }
        }
        return flag.equals(TaskStatus.EXECUTOR_COTACT_STATUS.getStatus());
    }

    /**
     * 批量删除任务
     * @param taskIds 任务ID集合
     * @return 结果集
     */
    @Override
    public StringBuffer  removeTaskBySelect(List<Long> taskIds) {
        AtomicInteger flag = new AtomicInteger();

        StringBuffer stringBuffer = new StringBuffer();

        //逐条验证任务状态
        taskIds.forEach(id->{

            flag.set(TaskStatus.NOT_IMPLEMENTED_STATUS.getStatus());

            if(taskInfoDao.findById(id).get().getExeStatus().equals(TaskStatus.EXECUTING_STATUS.getStatus())){

                //正在执行任务 删除
                if(taskInfoMapper.removeTaskByTaskId(id)>TaskStatus.NOT_IMPLEMENTED_STATUS.getStatus()){
                    //删除关联数据
                    taskInfoMapper.removeRelevancePlan(id);
                    taskInfoMapper.removeRelevanceInput(id);
                    //累加操作
                    flag.incrementAndGet();
                }

                if(flag.get()==TaskStatus.NOT_IMPLEMENTED_STATUS.getStatus()){
                    stringBuffer.append(taskInfoDao.findById(id).get().getName());
                }
            }
        });
        return stringBuffer;
    }

    /**
     * 读取excel返回JSONSting
     * @param file
     * @return
     */
    @Override
    public String readExcelFile(MultipartFile file)  {

        File file1 = null;
        try {
            // 调用MultiparFileToFileUtil将MultipartFile转换为File
            file1  = MultiparFileToFileUtil.multipartFileToFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //调用easyexcel模块中的EasyExcelFactory方法对数据进行读取 sheet和headRowNumber 是读取excel中的行和列
        List<TaskExcel> objects1 = EasyExcel.read(file1, TaskExcel.class, new ExcelModelListener()).sheet().headRowNumber(0).doReadSync();
        for (TaskExcel taskExcel : objects1) {
            System.out.println(taskExcel);
            dao.save(taskExcel);
        }
        //将查询出的数据转换为JSONString类型

        return null;
    }

    @Override
    public TaskInfo findById(Long id) {
        return taskInfoMapper.findById(id);
    }


}
